package com.zy.chat.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zy.chat.service.SaveGroupMessageService;
import com.zy.chat.vo.Groupmsgs;
import com.zy.chat.vo.RequestParams;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "groupmsgcontroller")
public class GroupMsgController {


    @Autowired
    private SaveGroupMessageService groupMessageService;
    @PostMapping(value = "list")
    public ResponseEntity<Groupmsgs> search(@RequestBody RequestParams params) {
        return new ResponseEntity<Groupmsgs>( groupMessageService.search(params), HttpStatus.OK);
    }

    @GetMapping(value = "getfile")
    public  ResponseEntity<List<String>> getfile(@RequestParam("file") MultipartFile file, HttpServletRequest  singleMessages) {
        String filename = file.getOriginalFilename();
        System.out.println(filename);
        String username = singleMessages.getParameter("username");
        String touser = singleMessages.getParameter("touser");
        String type = singleMessages.getParameter("type");
        String chattype = singleMessages.getParameter("Single");
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI5tQszWHSEfsHgMDnAKVP";
        String accessKeySecret = "6GKLQnypV8HGNJizymCiAxsD2AbEy0";
        String bucketname = "zzynb-bucket";
        LocalDate localDate = LocalDate.now();
        String objectName = localDate + "/" + filename;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ArrayList<String> list;
        try {
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucketname, filename, inputStream);
            Date date = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7);
            String url = ossClient.generatePresignedUrl(bucketname, objectName, date).toString();
            list = new ArrayList<>();
            list.add(filename);
            list.add(url);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            ossClient.shutdown();
        }
        return new ResponseEntity<List<String>>(list, HttpStatus.OK);
    }
}
